package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 找出所有和为target的数组
 */
public class Solution28 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //创建二维数组存放结果
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backtracting(res,new ArrayList<>(),candidates,target,0,0);
        return res;
    }

    public void backtracting(List<List<Integer>> res,List<Integer> path,
                             int[] candidates, int target,int sum,int startIndex){
        //首先判断相等的情况
        if(sum == target){
            res.add(new ArrayList<>(path));
            return ;
        }
        //判断大于的情况
        for(int i = startIndex ; i < candidates.length ; i++){
            if(sum + candidates[i] > target){
                break;
            }
            //小于的话就继续添加直到抖索到目标
            path.add(candidates[i]);
            backtracting(res,path,candidates,target,sum + candidates[i],i);
            path.remove(path.size() - 1);
        }
    }
}
